//
//  ZLPlusViewController.swift
//  新浪微博
//
//  Created by 朱玉龙 on 16/10/6.
//  Copyright © 2016年 朱玉龙. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZLPlusViewController: UIViewController {
    
    var textView: UITextView?
    var toolbar: UIToolbar?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", style: UIBarButtonItemStyle.done, target: self, action: #selector(back))
        navigationController?.navigationBar.isTranslucent = false
        setRightItem()
        setTitleView()
        setToolbar()
        setTextVeiw()
        setCollectionView()
        refisterkeyBoardObsever()
        self.textView?.becomeFirstResponder()
        postVC.textViewBlock = { [weak self] in
            
            self?.textView?.resignFirstResponder()
            
        }
    }
    
    private func refisterkeyBoardObsever() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChangFrame(n:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    @objc private func back() {
        
        dismiss(animated: true, completion: nil)
        
    }
    //提交
    @objc private func rightItemClick() {
        SVProgressHUD.show()
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        let parameters = ["access_token" : ZLOAthorViewModel.shareOAthor.account?.access_token ?? "", "status": self.textView?.text ?? ""]
        if images?.count == 0 {
        ZLNetworkingTools.sharedTools.loadData(method: .POST, urlString: urlString, parameters: parameters) { (_, error) in
            
            
                if error == nil  {
                    SVProgressHUD.dismiss()
                    SVProgressHUD.showSuccess(withStatus: "发送成功")
                    return
                }
                SVProgressHUD.dismiss()
                SVProgressHUD.showError(withStatus: "加载失败,请检测网络")
            }
        } else {
            
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            ZLNetworkingTools.sharedTools.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
                //需要将上传的二进制文件拼接到formdata
                
                /*
                 1. withFileData 需要上传的文件的二进制数据
                 2. name: 服务器接收的字段  'pic'
                 3. fileName: 服务器存储的名称  传或者不传 无所谓 新浪微博有自己的一套文件命名规则
                 4. mimeType 上传的文件的类型  application/octet-stream 忽略文件类型
                 */
                let imageData = UIImagePNGRepresentation((images?.last)!)
                formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "hdhdhdhdh", mimeType: "application/octet-stream")
                }, progress: nil, success: { (_, _) in
                    SVProgressHUD.showSuccess(withStatus: "发布图片微博成功,棒棒哒!")
                }, failure: { (_, error) in
                    print(error)
                    SVProgressHUD.showError(withStatus: "发布微博失败,请检查网络")
            })
        
//             urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
//            
//            ZLNetworkingTools.sharedTools.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
//                let imageData = UIImagePNGRepresentation((images?.last)!)
//                formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "wu", mimeType: "application/octet-stream")
//                
//                }, progress: nil, success: { (_, _) in
//                    SVProgressHUD.showSuccess(withStatus: "发布微博成功")
//                    SVProgressHUD.dismiss()
//                }, failure: { (_, error) in
//                    print(error)
//                    SVProgressHUD.showError(withStatus: "发布微博失败,请检查网络")
//                    SVProgressHUD.dismiss()
//            })
        }
    }
    //键盘检测
    @objc private func keyboardChangFrame(n: Notification) {
        let rect = n.userInfo?["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        let frame = rect.cgRectValue
        
        UIView.animate(withDuration: 0.25) {
            
            self.toolbar?.snp.updateConstraints({ (make) in
                
                make.bottom.equalTo(self.view).offset(-(screenHeight - frame.origin.y))
            })
        }
        
        self.view.layoutIfNeeded()
        
    }
    //MARK:底部导航条点击方法
    @objc private func buttonClick(btn: UIButton) {
        
        switch btn.tag {
        case 0:
              print("发微博")
        case 1:
        postVC.addBtnClick()
        case 2:
            print("@")
        case 3:
            if self.textView?.isFirstResponder == false {
                self.textView?.becomeFirstResponder()
            }
          self.textView?.inputView = self.textView?.inputView == nil ? emojiView : nil
            self.textView?.reloadInputViews()
        case 4:
            print("留用")
        default:
            print("乱点")
        }
        
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK:设置添加图片师徒
    private func setCollectionView() {
       self.addChildViewController(postVC)
        self.view.addSubview(postVC.view)
        postVC.view.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
        postVC.view.snp.makeConstraints { (make) in
           
            make.top.equalTo((self.textView?.snp.bottom)!)
           make.leading.trailing.bottom.equalTo(self.view)
        }
        self.view.bringSubview(toFront: self.toolbar!)
        postVC.itemHidden = {
            
            self.navigationItem.rightBarButtonItem?.isEnabled = images?.count != 0
        }
        postVC.view.isHidden = true
        
       
    }
    
    
    //MARK:导航条中间
    private func setTitleView() {
        
        let title = ZLOAthorViewModel.shareOAthor.account?.name == nil ? "发布微博" : "发布微博\n" + (ZLOAthorViewModel.shareOAthor.account?.name)!
        
        let attrString = NSMutableAttributedString(string: title)
        
        if ZLOAthorViewModel.shareOAthor.account?.name == nil {
            return
        }
        
        let range = (title as NSString).range(of: (ZLOAthorViewModel.shareOAthor.account?.name)!)
        //warning
        attrString.addAttributes([NSForegroundColorAttributeName : UIColor.orange, NSFontAttributeName: UIFont.systemFont(ofSize: 12)], range: range)
        
        let label = UILabel(title:"", color: UIColor.darkGray, fontSize: 15)
        label.attributedText = attrString
        label.numberOfLines = 0
        label.frame = CGRect(x: 0, y: 0, width: 60, height: 36)
        label.textAlignment = .center
        navigationItem.titleView = label
        
    }
    
    private func setRightItem() {
        
        let btn = UIButton(title: "提交", titleColor: UIColor.darkGray, fontSize: 15)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        btn.frame = CGRect(x: 0, y: 0, width: 60, height: 36)
        btn.addTarget(self, action: #selector(rightItemClick), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: btn)
        self.navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    private func setToolbar() {
        
        let toolbar = UIToolbar()
        self.toolbar = toolbar
        view.addSubview(toolbar)
        
        toolbar.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(36)
        }
        
        let imageArray = ["compose_keyboardbutton_background",
                          "compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_trendbutton_background"]
        var items = [UIBarButtonItem]()
        for i in 0..<5 {
            
            let btn = UIButton()
            btn.setImage(UIImage(named:imageArray[i]), for: .normal)
            btn.setImage(UIImage(named:imageArray[i] + "_highlighted"), for: .highlighted)
            btn.tag = i
            btn.sizeToFit()
            btn.addTarget(self, action: #selector(buttonClick(btn:)), for: .touchUpInside)
            
            let btnItem = UIBarButtonItem(customView: btn)
            items.append(btnItem)
            
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        toolbar.items = items
    }
    let placeHolder = UILabel(title: "我的大刀已经饥渴难耐", color: UIColor.lightGray, fontSize: 15)
    private func setTextVeiw() {
        let textVeiw = UITextView()
        view.addSubview(textVeiw)
        self.textView = textVeiw
        textVeiw.backgroundColor = UIColor.red
        textVeiw.textColor = UIColor.darkGray
        textVeiw.font = UIFont.systemFont(ofSize: 15)
        textVeiw.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(self.view)
            make.height.equalTo(self.view.bounds.height / 3)
        }
        textVeiw.delegate = self
        textVeiw.keyboardDismissMode = .onDrag
        textVeiw.alwaysBounceVertical = true
        textVeiw.addSubview(placeHolder)
        placeHolder.snp.makeConstraints { (make) in
            make.leading.equalTo(self.view).offset(5)
            make.top.equalTo(self.view).offset(8)
        }
        
    }
    
    lazy var emojiView: ZLEmojiInputView = {
       
        let emoji = ZLEmojiInputView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: emojiInputViewH))
        
        return emoji
    }()
    
    lazy var postVC: ZLPostImageController = {
        let layout = UICollectionViewFlowLayout()
        let margin = (screenWidth - 3 * plusItemW) / (3 + 1)
        layout.itemSize = CGSize(width: plusItemW, height: plusItemW)
        layout.minimumInteritemSpacing = margin
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        let vc = ZLPostImageController(collectionViewLayout: layout)
        vc.collectionView?.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        return vc
    }()

}




extension ZLPlusViewController:UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        self.placeHolder.isHidden = (self.textView?.hasText)!
        self.navigationItem.rightBarButtonItem?.isEnabled = (self.textView?.hasText)!
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.textView?.resignFirstResponder()
    }
    
}

